<template>
	<scroll-view scroll-y class="container" :style="{height: 'calc(100vh - ' + containerOutsideHeight + 'px)'}">
		<view class="fill-report">
			<view class="form">
				<view @click="buildDatePicker = true" class="form-item">
					<view class="label required">維修日期</view>
					<view class="form-content">
						<view class="form-text">{{ fillForm.repairDate  || ''}}</view>
						<u-icon name="arrow-down" color="#a7aebd" size="16"></u-icon>
					</view>
				</view>

				<view class="form-item" @click="showOrderType = true">
					<view class="label required">訂單類別</view>
					<view class="form-content">
						<view class="form-text">{{ fillForm.orderType || '' }}</view>
						<u-icon name="arrow-down" color="#a7aebd" size="16"></u-icon>
					</view>
				</view>

				<view class="form-item" @click="selectOrderNum">
					<view class="label required">訂單編號</view>
					<view class="form-content">
						<view class="form-text">{{ fillForm.orderNo || '' }}</view>
						<u-icon name="arrow-down" color="#a7aebd" size="16"></u-icon>
					</view>
				</view>

				<view class="form-item">
					<view class="label" style="padding-left: 10rpx;">站點位置</view>
					<view class="form-content">
						<view class="form-text" style="max-width: 500rpx;text-align: right;">{{ fillForm.location || '' }}</view>
					</view>
				</view>

				<view class="form-item">
					<view class="label" style="padding-left: 10rpx;">所屬項目</view>
					<view class="form-content">
						<view class="form-text">{{ fillForm.pmName || '' }}</view>
					</view>
				</view>
			</view>
			<view class="txt-box">
				<view class="left">維修病害</view>
				<view class="right" @click="selectDisease">選擇</view>
			</view>
			<view v-if="fillForm.PlanRepairDiseases && fillForm.PlanRepairDiseases.length">
				<u-checkbox-group v-model="selectedDisease" placement="column">
					<view class="form"  v-for="(item,index) in fillForm.PlanRepairDiseases" :key="index">
						<view v-if="item.isChecked">
							<view style="height: 30rpx;background-color:#f5f7fa ;"></view>
							<view style="font-weight: 600;font-size: 36rpx;color: #445469;margin: 16rpx 30rpx;">{{ item.orderNo || '' }}</view>
							<view class="form-item none">
								<view class="label">病害位置:{{ item.location || '' }}</view>
								<view class="form-text" style="color:#FF6A6A ;" @click="delRepairItem(index,item)" v-if="!(item.child && item.child.length && item.isChecked)">刪除</view>
							</view>
							<view class="form-item none">
								<view class="label">歷程:{{ item.subLocation || '' }}<view class="icon">{{ item.priority || '' }}</view></view>
							</view>
							<view class="form-item none">
								<view class="label">
									<view class="form-text" style="max-width: 680rpx;">病害描述:{{ item.defectDescription }}</view>
								</view>
							</view>
							<view class="form-item none" style="padding-bottom: 20rpx;">
								<view class="label">病害編號:{{ item.defectNo || ''}}</view>
							</view>
						</view>
						<view v-if="item.child && item.child.length">
							<view class="form-item dash" v-for="(item2, index2) in item.child.filter(i => i.isChecked)" :key="index2">
								<view class="label">{{ item2.defectNo || '' }}-{{item2.state  || ''}}</view>
								<view class="form-content">
										<view  class="form-text" style="color:#FF6A6A ;"  @click="delRepairItem(index,item2)" v-model="item2.id">删除</view>
								</view>
							</view>
						</view>
					</view>
				</u-checkbox-group>
			</view>
			<u-empty  v-else mode="data" icon="http://cdn.uviewui.com/uview/empty/data.png"></u-empty>
			<u-picker :show="showOrderType" :columns="typeColumns" @confirm="fnSure" @cancel="showOrderType = false" keyName="name"></u-picker>
			<u-datetime-picker @confirm="confirmBuildEndDate" @cancel="buildDatePicker = false" v-model="timeVal"
				:show="buildDatePicker" :minDate="(new Date()).getTime()" mode="date" />
			<view class="footer-button">
				<view class="button-placeholder"></view>
				<view class="button-group">
					<button @click="clickSubmit" :loading="isLoading" class="button-primary">提交</button>
				</view>
			</view>
		</view>
	</scroll-view>
</template>

<script>
	import { mapGetters } from "vuex";
	import { getSystemHeightInfo, isPositiveInteger, imgFun, getFormCheckResult } from "@/utils/common.js";
	import { handleFormatDate, compareDate } from "@/utils/date.js";
	import fileMixin from "@/mixins/file.js";
	import mixins from "@/utils/mixins.js"
	import { hkRepairPlan_save } from "@/api/HongKong/hkAttendanceSheet.js";
	export default {
		name: "fill-report",
		mixins: [fileMixin, mixins],
		data() {
			return {
				// 容器之外的高度
				containerOutsideHeight: 0,
				timeVal: Number(new Date()),
				// 填报表单
				fillForm: {
					hkOrderId: undefined,
					repairDate: '',
					orderType:'',
					orderNo:'',
					location:'',
					pmName:'',
					PlanRepairDiseases:[]

				},
				buildDatePicker: false,
				// 是否在加载中
				isLoading: false,
				showOrderType:false,
				typeColumns:[[]],
				selectedDisease:[]
			}
		},
		computed: {
			...mapGetters(['dictMap'])
		},
		watch: {},
		mounted() {
			this.initContainerData();
			this.typeColumns = [this.$store.getters.dictMap['xgwb_order_type']]
		},

		methods: {
			selectOrderNum() {
				if(!this.fillForm.orderType) return this.$message('请先选择订单类别')
				this.$set(this.fillForm, 'PlanRepairDiseases', [] )
				uni.navigateTo({
					url:`/subpackage-enginner/pages/engineeringMaintenance/personnelAttendance/select/select-order?type=${this.fillForm.orderType}`,
					events: {
						getOrderInfo: (data) => {
							console.log(data.data)
							this.$set(this.fillForm, 'pmName', data.data.pmName)
							this.$set(this.fillForm, 'location', data.data.lineName && data.data.lineSiteSectionName ? `${data.data.lineName}${data.data.lineSiteSectionName}` : '' )
							this.$set(this.fillForm, 'lineSiteSectionName', data.data.lineSiteSectionName)
							this.$set(this.fillForm, 'hkOrderId', data.data.id)
							this.$set(this.fillForm, 'orderNo', data.data.orderNo || data.data.orderNo2)
						}
					},
					success: (res) => {
						res.eventChannel.emit('sendOrder', {
							data:this.fillForm.hkOrderId || ''
						})
					}
				})
			},
			listToTree(data) {
			    // 先生成parent建立父子关系
			    const obj = {};
			    data.forEach(item => {
			        obj[item.id] = item;
			    });
			    const parentList = [];
			    data.forEach(item => {
			        const parent = obj[item.parentId];
			        if (parent) {
			            // 当前项有父节点
			            parent.child = parent.child || [];
			            // 将父级的信息也包含在子级中
			            item.location = parent.location
						item.subLocation = parent.subLocation
						item.defectDescription = parent.defectDescription
						item.priority = parent.priority
						item.parentDefectNo = parent.defectNo
			            parent.child.push(item);
			        } else {
			            // 当前项没有父节点 -> 顶层
			            parentList.push(item);
			        }
			    });
			    return parentList;
			},
			selectDisease() {
				if(!this.fillForm.hkOrderId) return this.$message('请先选择订单编号')
				uni.navigateTo({
					url:`/subpackage-enginner/pages/engineeringMaintenance/hongKong/select/select-diseases?id=${this.fillForm.hkOrderId}`,
					events: {
						getRepairDiseaseInfo: (data) => {
							console.log(data)
							this.fillForm.PlanRepairDiseases = data.data
							this.selectedDisease = data.idsList
							console.debug(this.fillForm.PlanRepairDiseases, '===---999')
							
						}
					},
					success: (res) => {
						res.eventChannel.emit('sendRepairDisease', {
							// data:this.fillForm.PlanRepairDiseases || []
							data:this.selectedDisease || []
						})
					}
				})
			},
			delRepairItem(index, obj) {
				// if(obj.parentId) {
				// 	for(let item of this.fillForm.PlanRepairDiseases) {
				// 		if(item.id === obj.parentId) {
				// 			let index1 = item.child.findIndex(item => item.id === obj.id)
				// 			item.child.splice(index1, 1)
				// 			this.selectedDisease = this.selectedDisease.filter(fi => fi !== obj.id)
				// 		}
				// 	}
				// }else {
				// 	this.fillForm.PlanRepairDiseases.splice(index, 1);
				// 	this.selectedDisease = this.selectedDisease.filter(fi => fi !== obj.id)
				// }
				if (Array.isArray(this.fillForm.PlanRepairDiseases[index].child)) {
					for (const index1 in this.fillForm.PlanRepairDiseases[index].child) {
						if(this.fillForm.PlanRepairDiseases[index].child[index1].id === obj.id) {
							this.fillForm.PlanRepairDiseases[index].child.splice(index1, 1)
							break
						}
					}
				}
				if (Array.isArray(this.fillForm.PlanRepairDiseases[index].child)) {
					const array = this.fillForm.PlanRepairDiseases[index].child.filter(item => item.isChecked)
					if (!array.length) {
						this.fillForm.PlanRepairDiseases.splice(index, 1)
					}
				} else {
					this.fillForm.PlanRepairDiseases.splice(index, 1)
					
				}
				this.selectedDisease = this.selectedDisease.filter(fi => fi !== obj.id)
				console.log(this.fillForm.PlanRepairDiseases, index, obj)
			},
			/** 初始化容器数据 */
			initContainerData() {
				const { stateHeight, bottomHeight, navbarHeight } = getSystemHeightInfo();
				this.containerOutsideHeight = stateHeight + bottomHeight + navbarHeight + 70;
			},
			fnSure(obj) {
				// console.log(obj,'00')
				if(obj.value[0].name !== this.fillForm.orderType) {
					this.$set(this.fillForm, 'pmName', '')
					this.$set(this.fillForm, 'location', '' )
					this.$set(this.fillForm, 'lineSiteSectioneName', '')
					this.$set(this.fillForm, 'hkOrderId', '')
					this.$set(this.fillForm, 'orderNo', '')
					this.$set(this.fillForm, 'PlanRepairDiseases', [] )
				}
				this.fillForm.orderType = obj.value[0].name
				this.showOrderType = false
			},
			flatten(arr) {
				return arr.reduce((result, item) => {
					return result.concat(item, Array.isArray(item.child) ? this.flatten(item.child) : []);
				}, []);
			},

			/** 保存每日交底填报的内容 */
			handleSaveFilleport() {
				this.fillForm.PlanRepairDiseases =  this.flatten(this.fillForm.PlanRepairDiseases).filter(it => this.selectedDisease.includes(it.id)).map(it1 => ({
					hkDiseaseOrderId: it1.id, 
					diseaseNo: it1.state ? `${it1.defectNo}-${it1.state}` : it1.defectNo,
				}))
				if(this.fillForm.PlanRepairDiseases.length === 0) {
					return this.$message('請選擇維修病害！')
				}
				return new Promise(resolve => {
					hkRepairPlan_save(this.fillForm).then(res => {
						uni.showToast({
							title: res.message,
							icon: "none",
							duration: 1000,
						});
						this.initFillForm();
						resolve();
					});
				});
			},

			/** 点击提交按钮 */
			async clickSubmit() {
				console.log(this.fillForm, '==-')
				// 表单校验...
				// if (!getFormCheckResult(this.fillForm, ['location', 'hkOrderId', 'pmName', 'PlanRepairDiseases'])) {
				// 	uni.showToast({
				// 		title: "请检查表单是否填写完整",
				// 		icon: "none"
				// 	});
				// 	return;
				// }
				if(!this.fillForm.repairDate)  return this.$message('請選擇維修日期！')
				if(!this.fillForm.orderNo)  return this.$message('請選擇訂單類別！')
				if(!this.fillForm.orderType)  return this.$message('請選擇訂單編號！')
				
				// 调用接口...
				if (!this.isLoading) {
					this.isLoading = true;
					await this.handleSaveFilleport();
					this.isLoading = false;
				}
			},

			/** 初始化表单 */
			initFillForm() {
				this.$set(this.fillForm, 'hkOrderId', undefined)
				this.$set(this.fillForm, 'repairDate', '')
				this.$set(this.fillForm, 'orderType', undefined)
				this.$set(this.fillForm, 'orderNo', undefined)
				this.$set(this.fillForm, 'location', undefined)
				this.$set(this.fillForm, 'pmName', undefined)
				this.$set(this.fillForm, 'PlanRepairDiseases', [])
				this.selectedDisease = []
			},
			confirmBuildEndDate(event) {
				this.fillForm.repairDate = handleFormatDate(event.value, 1)
				this.buildDatePicker = false;
			},
		}
	}
</script>

<style scoped lang="scss">
	.fill-report {
		.form {
			background: #fff;
			// padding-top: 26upx;

			.form-item {
				height: 100upx;
				display: flex;
				align-items: center;
				justify-content: space-between;
				margin: 0 30upx;
				border-bottom: 1px solid #e2e5ed;

				&:last-of-type {
					border-bottom: none;
				}

				.label {
					color: #445469;
					line-height: 34upx;
					flex-shrink: 0;
					display: flex;
					align-items: center;
					.icon {
						width: 50rpx;
						padding: 6rpx 20rpx;
						clip-path: polygon(15rpx 0, 100% 0, calc(100% - 15rpx) 52rpx, 0% 52rpx);
						height: 24rpx;
						font-size: 26rpx;
						font-family: PingFang SC-Bold, PingFang SC;
						font-weight: bold;
						color: #FFFFFF;
						line-height: 24rpx;
						background: linear-gradient(90deg,#ff5f2c  0%, #ff9e39 100%);
						text-align: center;
						opacity: 1;
					}
				}

				.form-content {
					color: #22204e;
					display: flex;
					align-items: center;
				}

				.form-text {
					line-height: 58upx;
					white-space: nowrap;
					overflow: hidden;
					text-overflow: ellipsis;
					max-width: 302upx;
				}

				.form-text.none {
					opacity: .7;
					font-size: 30rpx;
				}

				.u-icon {
					margin-left: 40upx;
				}

				.uicon-close-circle-fill {
					margin-left: 32upx;
				}

				.u-input {
					width: 340upx;
					text-align: right;

					::v-deep .u-input__content__field-wrapper {
						margin-right: 24upx;
					}

					::v-deep .uni-input-wrapper {
						text-align: right;
					}
				}

				.u-switch {
					margin-right: 30upx;
				}
			}
			.form-item.none {
				border-bottom: none;
				height: 60upx;
			}
			
			.form-item.dash {
				border-top: 1px dashed #E0E7F6; 
				border-bottom: 1px dashed #E0E7F6;
				&:last-of-type {
					border-bottom: none;
				}
			}


			.no-inline {
				display: block;
				height: auto;

				.label {
					line-height: 100upx;
				}
			}
		}


	}

	.fill-report.mar-t {
		padding-top: 26upx;
	}

	.footer-button {
		height: 154upx;

		.button-placeholder {
			height: 100%;
		}

		.button-group {
			height: 154upx;
			padding: 30upx;
			box-sizing: border-box;
			background: #fff;
			position: fixed;
			width: 100vw;
			bottom: 0;
			z-index: 1;

			.button-primary {
				background: #2f80ed;
				border-radius: 4upx;
				color: #fff;
				font-weight: bold;
				line-height: 92upx;
				text-align: center;
			}
		}
	}

	.required {
		&::before {
			content: "*";
			color: #ff6a6a;
		}
	}

	.uni-group {
		display: flex;
		align-items: center;
	}
	.txt-box {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 20rpx 20rpx 0 20rpx;
		.left {
			font-weight: bold;
			font-size: 36rpx;
	
			&::before {
				content: "*";
				color: #ff6a6a;
			}
		}
	
		.right {
			width: 96rpx;
			height: 60rpx;
			background: #2F80ED;
			border-radius: 8rpx;
			font-weight: 500;
			font-size: 28rpx;
			color: #FFFFFF;
			line-height: 60rpx;
			text-align: center;
		}
	}
</style>